'use strict';

require('sugar');
var fs = require('fs');
var http = require('http');
var https = require('https');

function readHttpsOptions(options) {
  // NOTE: https.options support outlined on
  // http://nodejs.org/api/tls.html#tls_tls_createserver_options_secureconnectionlistener
  var readFileOptions = ['pfx', 'key', 'cert', 'ca'];
  var keys = Object.keys(options);
  keys.each(function (key) {
    if (readFileOptions.find(key)) {
      if (Object.isArray(options[key])) {
        options[key].each(function (element, index, src) {
          src[index] = fs.readFileSync(element);
        });
      } else {
        options[key] = fs.readFileSync(options[key]);
      }
    }
  });
}

module.exports.startServer = function (app, options) {
  var logger = options.logger || console;
  var bindIP = options.bindIP;
  var port = options.port || 9100;
  var isHttps = options.https.enabled || false;
  var httpsOptions = options.https.options || {};
  var server;

  if (!options.rejectUnauthorized) {
    process.env.NODE_TLS_REJECT_UNAUTHORIZED = '0';
  }

  if (options.https.enabled) {
    logger.info('SSL is enabled');
    readHttpsOptions(options.https.options);
    var passwordUtils = require('./password')(options);
    options.https.options.passphrase = passwordUtils.decrypt2(options.https.options.passphrase, options.keyfile);
  }

  if (bindIP && bindIP === '0.0.0.0') {
    bindIP = undefined;
  }

  if (isHttps) {
    https.globalAgent.maxSockets = options.maxSockets || 1000;
    server = https.createServer(httpsOptions, app);
  } else {
    http.globalAgent.maxSockets = options.maxSockets || 1000;
    server = http.createServer(app);
  }

  if (bindIP) {
    server.listen(port, bindIP, function () {
      return logger.info('Server is listening on ' + bindIP + ':' + port);
    });
  } else {
    server.listen(port, function () {
      return logger.info('Server is listening on ' + port);
    });
  }

  server.on('error', function (err) {
    logger.error(Date.create(Date.now()) + ' Error encountered');
    logger.error(err);
  });
};